import bean.Component;
import bean.ComponentStateBean;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import ui.ColumnDialog;
import utils.AndroidUtils;

import java.io.IOException;
import java.util.*;

public abstract class BaseModelsOperation extends AnAction {
    private ArrayList<String> mLines;
    private VirtualFile mFile;

    @Override
    public void actionPerformed(AnActionEvent e) {
        // 测试代码
        Project project = e.getData(PlatformDataKeys.PROJECT);
        if (project != null) {
            mFile = AndroidUtils.getGeneralCompileSetting(project);
            if (mFile != null) {
                try {
                    //获取generalCompileSetting 文件下的 generalCompileEnv_ThirdAarLib 字段
                    //按照过滤条件获取已经配置的信息
                    String text = AndroidUtils.readFilterFileSting(mFile);
                    //全量读出配置文件信息
                    mLines = new ArrayList<String>(Arrays.asList(AndroidUtils.readFileSting(mFile).split("\n")));
                    String[] split = text.split("\n");
                    ArrayList<String> components = new ArrayList<>();
                    for (String s : split) {
                        if (s.startsWith("'SCP_")) {
//                            System.out.println(" component " + s);
                            components.add(s.replace(",", ""));
                        }
                    }
                    //过滤到的配置文件中设置的所有组件
                    showDialog(components);
                } catch (IOException ioException) {
                    System.out.println(" plugin message error " + ioException.getMessage());
                }
            }
        }
    }

    /**
     * 显示UI设置界面
     */
    private void showDialog(ArrayList<String> enableList) {
        //默认的所有组件
        ArrayList<Component> componentsList = getComponents();
        for (Component component : componentsList) {
            //先读取配置文件中的所有组件信息，如果包含配置的组件,则在UI界面显示为勾选状态，否则，显示为非勾选状态
            if (enableList.toString().contains(component.getName())) {
                component.setEnable(true);
            }
        }
        ColumnDialog dialog = new ColumnDialog(componentsList);
        dialog.setOnGenerateListener(new ColumnDialog.OnGenerateListener() {
            @Override
            public void onGenerate(ArrayList<ComponentStateBean> functions, ArrayList<ComponentStateBean> cores) {
                //返回的功能组件和核心组件勾选状态
                // 如果功能组件中存在没有挂载的组件，并且在原来配置文件中存在，则注释掉，否则不用管
                StringBuilder functionComponent = new StringBuilder();
                ArrayList<String> unNeed = new ArrayList<>();
                HashMap<String, Boolean> need = new HashMap<>();
                for (ComponentStateBean function : functions) {
                    if (function.isEnable()) {
                        //如果功能组件需要挂载，需要在原组件中查找，是否存在
                        need.put("'" + function.getName() + "'" + ",", false);
                    } else {
                        //如果是非挂载的组件
                        unNeed.add("'" + function.getName() + "'" + ",");
                    }
                }
                Set<Map.Entry<String, Boolean>> entries = need.entrySet();

                for (String line : mLines) {
                    //如果在需要挂载的组件中，原组件存在，则忽略
                    for (Map.Entry<String, Boolean> entry : entries) {
                        if (line.startsWith(entry.getKey())) {
                            entry.setValue(true);
                        }
                    }
                }

                for (int i = 0; i < mLines.size(); i++) {
                    for (String index : unNeed) {
//                        System.out.println(" INDEX DDD " + mLines.get(i) + " index " + index);
                        if (mLines.get(i).startsWith(index)) {
//                            System.out.println(" INDEX ooooo ");
                            mLines.set(i, "//" + mLines.get(i));
                        }
                    }
                }

                for (Map.Entry<String, Boolean> entry : entries) {
                    if (!entry.getValue()) {
                        functionComponent.append(entry.getKey()).append("\n");
                    }
                }

                StringBuilder coreComponent = new StringBuilder();
                for (ComponentStateBean core : cores) {
                    //如果核心组件，需要强制挂载上去
                    //如果组件中不存在 则忽略再次添加组件
                    boolean addResult = true;
                    for (String line : mLines) {
                        //如果在需要挂载的组件中，原组件存在，则忽略
                        if (line.startsWith("'" + core.getName())) {
                            addResult = false;
                            break;
                        }
                    }

                    if (addResult) {
                        coreComponent.append("'").append(core.getName()).append("'").append(",").append("\n");
                    }
                }

                //清除掉注释的代码,替换成换行键
                for (int i = 0; i < mLines.size(); i++) {
                    if (mLines.get(i).startsWith("//'SCP_")) {
                        mLines.set(i, "");
                    }
                }

                StringBuilder content = new StringBuilder();
                boolean isAdd = false;
                for (String mLine : mLines) {
                    content.append(mLine).append("\n");
                    if (mLine.startsWith("'SCP_")) {
                        if ((coreComponent.toString().length() > 0 || functionComponent.toString().length() > 0) && !isAdd) {
                            isAdd = true;
                            content.append(coreComponent.toString()).append(functionComponent.toString());
                        }
                    }
                }
                AndroidUtils.writerFileSting(mFile, content.toString());
            }
        });
        dialog.pack();
        dialog.setVisible(true);

    }

    protected abstract ArrayList<Component> getComponents();
}
